import { Injectable } from '@nestjs/common';
import { CreateChatDto } from './dto/create-chat.dto';
import { UpdateChatDto } from './dto/update-chat.dto';
import { PrismaService } from '../../prisma/prisma.service';
import OpenAI from 'openai';
import { CurrentUser } from '../auth/user.decorator';

@Injectable()
export class ChatService {
  constructor(private prisma: PrismaService) {}
  private openai = new OpenAI({
    apiKey: process.env.OPENAI_API_KEY,
    baseURL: 'https://api.deepseek.com',
  });

  //创建聊天记录
  async create(payload: CreateChatDto, response, user: any) {
    const { message,conversationId } = payload;
    let allAnswer = '';
    try {
      const completion = await this.openai.chat.completions.create({
        model: 'deepseek-chat',
        messages: [
          { role: 'system', content: '你是一位专业的助手。请始终使用标准的Markdown格式回复。你的回答应该：\n1. 使用适当的标题层级(#, ##, ###)\n2. 正确使用列表符号和缩进\n3. 代码块使用```标记并注明语言\n4. 适当使用粗体、斜体等格式\n5. 保持段落间的空行' },
          { role: 'user', content: message },
        ],
        stream: true,
      });
      // 流式响应
      response.setHeader('Content-Type', 'text/event-stream');
      response.setHeader('Cache-Control', 'no-cache');
      response.setHeader('Connection', 'keep-alive');

      for await (const chunk of completion) {
        const content = chunk.choices[0].delta.content || '';
        response.write(`${content}`);
        allAnswer += content;
      }
      if (user) {
        // 如果没有提供conversationId，创建新对话
        let currentConversationId = conversationId;
        if (!currentConversationId) {
          const newConversation = await this.prisma.conversation.create({
            data: {
              userId: +user.userId,
              title: message,
            }
          });
          currentConversationId = newConversation.id;
        }

        await this.prisma.chatHistory.create({
          data: {
            content: message,
            role: 'user',
            userId: +user.userId,
            conversationId: currentConversationId,
          },
        });
        
        await this.prisma.chatHistory.create({
          data: {
            content: allAnswer,
            role: 'assistant',
            userId: +user.userId,
            conversationId: currentConversationId,
          },
        });
      }
      response.end();
      // 保存数据到数据库
    } catch (error) {
      console.log(`错误信息：${error}`);
      console.log(
        '请参考文档：https://help.aliyun.com/zh/model-studio/developer-reference/error-code',
      );
      response.end();
    }
  }


  // 获取特定对话的消息历史
  async findAll(response: any, user: any, payload: any) {
    const { conversationId } = payload
    if (!user) {
      return response.send({
        status: false,
        message: '未登录用户',
        data: []
      });
    }

    const where = {
      userId: +user.userId,
      ...(conversationId && { conversationId: +conversationId })
    };

    const messages = await this.prisma.chatHistory.findMany({
      where,
      orderBy: {
        createdAt: 'asc'
      }
    });

    response.send({
      status: true,
      data: messages,
    });
  }

  //删除聊天记录
  async delete(id: string) {
    try {
      if (!id) {
        // 全部删除
        const result = await this.prisma.chatHistory.deleteMany();
        return {
          status: true,
          message: `成功删除${result.count}条记录`,
        };
      }
  
      // 先检查记录是否存在
      const record = await this.prisma.chatHistory.findUnique({
        where: { id: parseInt(id) },
      });
  
      if (!record) {
        return {
          status: false,
          message: '记录不存在',
        };
      }
  
      // 删除单条记录
      await this.prisma.chatHistory.delete({
        where: { id : parseInt(id) },
      });
  
      return {
        status: true,
        message: '删除成功',
      };
    } catch (error) {
      console.error('删除失败:', error);
      return {
        status: false,
        message: '删除失败: ' + error.message,
      };
    }
  }


  // 获取用户的所有对话列表
  async getConversations(response:any,user: any) {
    if (!user) {
      response.send({
        status: false,
        message: '未登录用户',
        data: []
      });
    }
    const result = await this.prisma.conversation.findMany({
      where: {
        userId: +user.userId
      },
      orderBy: {
        updatedAt: 'desc'
      },
    });
    response.send({
      status: true,
      data: result
    })
  }

  // 创建新对话
  async createConversation(userId: number) {
    return await this.prisma.conversation.create({
      data: {
        userId: userId,
      }
    });
  }

  // 删除对话
  async deleteConversation(conversationId: number) {
    try {
      // 首先删除对话下的所有消息
      await this.prisma.chatHistory.deleteMany({
        where: {
          conversationId: conversationId
        }
      });

      // 然后删除对话本身
      await this.prisma.conversation.delete({
        where: {
          id: conversationId
        }
      });

      return {
        status: true,
        message: '对话删除成功'
      };
    } catch (error) {
      console.error('删除对话失败:', error);
      return {
        status: false,
        message: '删除对话失败: ' + error.message
      };
    }
  }
}
